import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_api.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_category.dart';
import 'package:schedule_self_client/common/simple_resp.dart';
import 'package:schedule_self_client/ui/components/task_category_select_dialog.dart';
import 'package:schedule_self_client/utils/time_util.dart';

class TaskDialog extends StatefulWidget {
  final Function okCallback;

  const TaskDialog({required this.okCallback})
      : super(key: const Key('task_dialog'));

  @override
  State<TaskDialog> createState() => _TaskDialogState();
}

class _TaskDialogState extends State<TaskDialog> {
  final _formKey = GlobalKey<FormState>();
  String _taskName = '';
  String? _taskDescription;
  DateTime? _deadline;
  TaskCategory? _taskCategory;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('添加任务'),
      content: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextFormField(
              onSaved: (value) {
                _taskName = value ?? '';
              },
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入任务名称';
                }
                return null;
              },
              decoration: const InputDecoration(
                  border: InputBorder.none,
                  hintText: '准备做什么？',
                  hintStyle: TextStyle(fontSize: 16)),
            ),
            TextFormField(
              onSaved: (value) {
                _taskDescription = value;
              },
              decoration: const InputDecoration(
                  border: InputBorder.none,
                  hintText: '任务描述',
                  hintStyle: TextStyle(fontSize: 12)),
            ),
            const SizedBox(height: 8),
            _buildDeadline(),
            const SizedBox(height: 8),
            _buildTaskCategorySelect(),
          ],
        ),
      ),
      actions: [
        TextButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: const Text('取消')),
        ElevatedButton(
            onPressed: () async {
              if (context.mounted) {
                bool? validateFlag = _formKey.currentState?.validate();
                if (validateFlag ?? false) {
                  _formKey.currentState?.save();
                  SimpleResp resp = await TaskApi.taskAdd(
                      name: _taskName,
                      description: _taskDescription,
                      deadline: _deadline != null
                          ? TimeUtil.formatTimeToBackend(_deadline!)
                          : null,
                      taskCategoryId: _taskCategory?.id);
                  if (resp.success) {
                    widget.okCallback();
                  }
                  Navigator.of(context).pop();
                }
              }
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).primaryColor,
            ),
            child: const Text(
              '确定',
              style: TextStyle(color: Colors.white),
            )),
      ],
    );
  }

  Widget _buildDeadline() {
    return Row(
      children: [
        Container(
          color: _deadline == null ? null : Theme.of(context).primaryColor,
          child: InkWell(
            onTap: () {
              _showDatePicker();
            },
            child: Row(
              children: [
                Icon(
                  Icons.calendar_today,
                  size: 14,
                  color: _deadline == null ? Colors.black : Colors.white,
                ),
                const SizedBox(width: 4),
                Text(
                  _deadline == null
                      ? '请设置截止日期'
                      : DateFormat('yyyy-MM-dd').format(_deadline!),
                  style: TextStyle(
                      fontSize: 14,
                      color: _deadline == null ? Colors.black : Colors.white),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTaskCategorySelect() {
    return Container(
      color:
          _taskCategory == null ? null : Color(int.parse(_taskCategory!.color)),
      child: InkWell(
        onTap: () async {
          TaskCategory selectTaskCategory = await showDialog(
              context: context,
              builder: (context) {
                return const TaskCategorySelectDialog();
              });
          setState(() {
            _taskCategory = selectTaskCategory;
          });
        },
        child: Row(
          children: [
            Icon(
              Icons.category,
              size: 14,
              color: _deadline == null ? Colors.black : Colors.white,
            ),
            const SizedBox(width: 4),
            Text(_taskCategory == null ? '请选择任务分类' : _taskCategory!.name,
                style: TextStyle(
                    fontSize: 14,
                    color: _deadline == null ? Colors.black : Colors.white))
          ],
        ),
      ),
    );
  }

  void _showDatePicker() async {
    DateTime? dateTime = await showDatePicker(
        context: context,
        firstDate: DateTime.utc(1970),
        lastDate: DateTime.utc(9999));
    if (dateTime != null) {
      setState(() {
        _deadline = dateTime;
      });
    }
  }
}
